﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace DFGK_WMS.Repository
{
    public class RoleRepository : BaseRepository<TRole>, IRoleRepository
    {
        public RoleRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddRole(TRole m)
        {
            try
            {
                var obj = Context.TRoles.FirstOrDefault(x => x.RoleCode == m.RoleCode);
                if(obj!=null)
                {
                    return false;
                }
                m.CreateUserId = m.NowUserId;
                m.CreateUserName = m.NowUserRealName;
                m.ModifyUserId = m.NowUserId;
                m.ModifyUserName = m.NowUserRealName;
                m.CreateDate= DateTime.Now;
                m.ModifyDate= DateTime.Now;
                Context.TRoles.Add(m);
                return Context.SaveChanges()>0;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelRole(int rid)
        {
            try
            {
                //判断角色表是否为空
                var robj = Context.TRoles.Find(rid);
                if(robj!=null)
                {
                    //删除角色
                    Context.TRoles.Remove(robj);
                    //删除用户角色关系表
                    var urobj = Context.TUserRoles.Where(x => x.RoleId == rid);
                    Context.TUserRoles.RemoveRange(urobj);
                    //查询角色菜单操作中该角色拥有的所有权限并删除
                    var rma = Context.TRoleMenuActions.Where(x => x.RoleId == rid);             
                        Context.TRoleMenuActions.RemoveRange(rma);
                    //查询角色仓库关系中该角色拥有的仓库并删除
                    var rw = Context.TRoleWarehouses.Where(x => x.RoleId == rid);
                        Context.TRoleWarehouses.RemoveRange(rw);
                }
                return Context.SaveChanges()>0;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 获取所有角色
        /// </summary>
        /// <param name="rname">用户名</param>
        /// <param name="state">状态</param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <param name="pageCount"></param>
        /// <returns></returns>
        public List<TRole> GetRoleList(string rname, int state, int pageIndex, int pageSize, out int totalCount)
        {
            try
            {
                var rlist = Context.TRoles.AsQueryable();
                //判断用户名称是否为空
                if (!string.IsNullOrEmpty(rname))
                {
                    rlist = rlist.Where(x => x.RoleName.Contains(rname));
                }
                //判断用户状态
                if (state != 3)
                {
                    rlist = rlist.Where(x => x.Status == state);
                }
                totalCount = rlist.Count();
                rlist = rlist.OrderBy(x=>x.DisplayOrder).Skip((pageIndex - 1) * pageSize).Take(pageSize);
                return rlist.ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 分配权限中的列表显示
        /// </summary>
        /// <returns></returns>
        public List<MenuDto> GetRoleMenuActionList()
        {
            var mlist = Context.TMenus.AsNoTracking().ToList();
            return GetRoleMenuActionLists(mlist, 0);
        }

        public List<MenuDto> GetRoleMenuActionLists(List<TMenu> list,int pid)
        {
            var alist = Context.TMenuActions.AsNoTracking().ToList();
            var malist = Context.TActions.AsNoTracking().ToList();
            return list.Where(x => x.ParentId == pid).Select(x => new MenuDto
            {
                id = x.Id,
                ParentId = x.ParentId,
                MenuUrl = x.MenuUrl,
                Meta = new MetaDto
                {
                    MenuName = x.MenuName,
                    MenuIcon = x.MenuIcon,
                },
                Status = x.Status,
                DisplayOrder = x.DisplayOrder,
                children = GetRoleMenuActionLists(list, x.Id),
                Action= MenuActionById(alist,malist, x.Id)
            }).OrderBy(x => x.DisplayOrder).ToList();
        }

        public static List<ActionDto> MenuActionById(List<TMenuAction> list,List<TAction> alist, int mid)
        {
            var lists=from a in list
                      join b in alist
                      on a.ActionId equals b.Id
                      where a.MenuId == mid
                      select b;
            return lists.Select(x => new ActionDto
            {
                Id = x.Id,
                ActionName=x.ActionName
            }).ToList();
        }

        /// <summary>
        /// 根据主键查询信息
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TRole RoleById(int rid)
        {
            try
            {
                var robj = Context.TRoles.Find(rid);
                return robj;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 修改角色
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdRole(TRole m)
        {
            try
            {
                var list = Context.TRoles.AsNoTracking().FirstOrDefault(x => x.Id!=m.Id && x.RoleCode==m.RoleCode);

                if(list!=null)
                {
                    return false;
                }
                           
                m.ModifyDate = DateTime.Now;
                m.ModifyUserId = m.NowUserId;
                m.ModifyUserName = m.ModifyUserName;
                Context.TRoles.Update(m);
                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
